#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#author:         rex
#blog:           http://iregex.org
#created:        2010-06-26 18:55
#lastedit:       2010-06-26 22:04

import re
from google.appengine.ext import db

class Snip(db.Model):
    subject=db.StringProperty()
    text=db.TextProperty()
    added=db.DateTimeProperty(auto_now_add=True)
    last_modi=db.DateTimeProperty(auto_now=True) 

class Tag(db.Model):
    t=db.StringProperty()

class TagSet(db.Model):
    t=db.ReferenceProperty(Tag)
    s=db.ReferenceProperty(Snip)    

class AddSnip():
    def __init__(self, msg, client):
        '''split the message to mutipars'''

        self.clt=client
        lines=re.split(u"(?u)\s*\n+\s*",msg)
        if len(lines)<3:
            self.clt.reply('''A code snipt should be at least 3 lines:
Subject,
#tag1 #tag2 ... #tagN  (tag is a MUST!)
Body''') 
            return

        self.sub=lines[0]
#        self.clt.reply("subject : "+self.sub)

        self.tag=lines[1]
#        self.clt.reply("tags: "+self.tag)

        body=lines[2:]
        self.body="\n".join(body) 

#        self.clt.reply("body: "+self.body)

    def Do(self):
        s=Snip()
                
        try:
            s.subject=self.sub
            s.text=self.body
            s.put()    
        except:
            self.clt.reply("Add Snip"+self.subject+" Error!")
            pass
    
        try:
            tags=re.findall(u"#((?u)\S+)", self.tag)
            for t in tags:
                tag=Tag()
                tagset=TagSet() 
                tag.t=t
                tag.put()
                tagset.t=tag.key() #added
                tagset.s=s.key() #added
                tagset.put()

            self.clt.reply("Snippet: *"+self.sub+"* with Tags: "+ " ".join(['_#'+x+'_' for x in tags])+" added!")

        except:
            self.clt.reply("Add Snippet *"+self.sub+"* Error!")

           




